package cn.com.ejiakanghu.service;

import cn.com.ejiakanghu.core.exceptions.BizException;
import cn.com.ejiakanghu.core.utils.RespUtil;
import cn.com.ejiakanghu.core.vo.BaseResult;
import cn.com.ejiakanghu.dto.*;
import cn.com.ejiakanghu.vo.OrderListVo;
import cn.com.ejiakanghu.vo.serviceorder.*;
import cn.com.ejiakanghu.vo.serviceorder.GoodsDataSku;
import cn.com.ejiakanghu.vo.serviceorder.GoodsSpecInfo;
import cn.com.ejiakanghu.vo.serviceorder.SkuDataInfo;
import cn.ejiakanghu.logistics.service.TakeOrderService;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.LitemallGoodsProductMapper;
import org.linlinjava.litemall.db.dao.app.AppGoodsMapper;
import org.linlinjava.litemall.db.dao.order_manage.*;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.jsonfield.LitemallGoodsProductSpecification;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.service.oder_manage.AgedmallServiceOrderService;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.app.StoreGoodsProductVo;
import org.linlinjava.litemall.db.vo.app.StoreGoodsVo;
import org.linlinjava.litemall.db.vo.service_order.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author huangfei
 * @create 2021-11-19 19:35
 */
@Service
@Transactional
public class AgeMallorderOnLineService {

    Logger logger = LoggerFactory.getLogger(AgeMallorderOnLineService.class);

    @Resource
    private AgedmallOnLineServiceOrderMapper agedmallOnLineServiceOrderMapper;

    @Resource
    private AgedmallOrderOperateLogMapper agedmallOrderOperateLogMapper;


    @Autowired
    private AgedmallStoreService agedmallStoreService;

    @Resource
    private AppGoodsMapper appGoodsMapper;

    @Autowired
    private AgedmallGoodsSpecificationInfoService agedmallGoodsSpecificationInfoService;

    @Resource
    private LitemallGoodsProductMapper litemallGoodsProductMapper;

    @Resource
    private AgedmallDepartmentMapper agedmallDepartmentMapper;

    @Resource
    private AgedmallDoctorInfoMapper agedmallDoctorInfoMapper;

    @Resource
    private LitemallUserMapper litemallUserMapper;

    @Resource
    private AgedmallServiceOrderMapper agedmallServiceOrderMapper;

    @Resource
    private AgedmallOnlineServiceMapper agedmallOnlineServiceMapper;

    @Resource
    private AgedmallOnlineServiceProductMapper agedmallOnlineServiceProductMapper;

    @Resource
    private AgedmallTagsMapper agedmallTagsMapper;

    @Resource
    private AgedmallServiceOrderManageMapper agedmallServiceOrderManageMapper;

    @Resource
    private AgedmallStoreGoodsMapper agedmallStoreGoodsMapper;

    @Resource
    private LitemallOrderMapper litemallOrderMapper;

    @Resource
    private LitemallGoodsSpecificationMapper litemallGoodsSpecificationMapper;

    @Autowired
    private TakeOrderService takeOrderService;

    @Resource
    private AgedmallServiceDepartmentMapper agedmallServiceDepartmentMapper;

    @Resource
    private AgedmallOnlineServiceRecordMapper agedmallOnlineServiceRecordMapper;

    @Autowired
    private AgedmallServiceOrderService agedmallServiceOrderService;

    @Resource
    private AgedmallTakeOrderRecordMapper agedmallTakeOrderRecordMapper;


    /**
     * 取消预约
     * @param serviceOrderId
     * @return
     */
    public BaseResult cacneSubscribe(String serviceOrderId, String status) {
        try {
            agedmallOnLineServiceOrderMapper.cacneSubscribe(serviceOrderId, status);

            //根据服务订单编号查询
            AgedmallServiceOrderExample example = new AgedmallServiceOrderExample();
            example.or().andOrderSnEqualTo(serviceOrderId);
            AgedmallServiceOrder agedmallServiceOrder = agedmallServiceOrderMapper.selectOneByExample(example);
            if(agedmallServiceOrder != null){
                //删除抢单信息
                AgedmallTakeOrderRecordExample agedmallTakeOrderRecordExample = new AgedmallTakeOrderRecordExample();
                agedmallTakeOrderRecordExample.or().andPrintIdEqualTo(agedmallServiceOrder.getId().intValue());
                agedmallTakeOrderRecordMapper.deleteByExample(agedmallTakeOrderRecordExample);
            }
            //增加订单记录日志
            //saveOperateLog(serviceOrderId,OrderOperateType.CANCEL_ORDER);
            return RespUtil.success();
        } catch (Exception e) {
            return RespUtil.fail();
        }
    }

    /**
     * 修改预约时间
     * @param serviceOrderId
     * @param subDate
     * @param subTime
     * @return
     */
    public BaseResult serviceEditSubDatetime(String serviceOrderId,String subDate,String subTime){
        try {
            String subscribeTime[] = subTime.split("~");
            //预约开始完整时间
            String fullAppointTime = subDate+" "+subscribeTime[0]+":"+"00";
            //预约时间
            String appointmentTime = subDate;
            //预约开始时间
            String startTime = subDate +" "+subscribeTime[0];
            //预约结束时间
            String endTime = subDate + " "+subscribeTime[1];
            agedmallOnLineServiceOrderMapper
                    .serviceEditSubDatetime(serviceOrderId,fullAppointTime,appointmentTime,startTime,endTime);
            //增加订单记录日志
            //saveOperateLog(serviceOrderId,OrderOperateType.SUBSCRIBE_ORDER);
            return RespUtil.success();
        }catch (Exception e){
            return RespUtil.fail();
        }
    }

    private String getOrderSn() {
        // 时间戳加自增数据库6位id
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        int number = add();
        return time + StringUtils.leftPad(number + "", 6, "0");
    }

    public int add(){
        AgedmallOnlineService agedmallOnlineService = new AgedmallOnlineService();
        agedmallOnlineService.setAddTime(LocalDateTime.now());
        agedmallOnlineService.setDeleted(false);
        agedmallOnlineServiceMapper.insert(agedmallOnlineService);
        return agedmallOnlineService.getId();
    }




    /**
     * 增加预约服务
     * @param serviceorder
     * @return
     */
    public BaseResult serviceCreateSub(Serviceorder serviceorder){
        try {
            AgedmallServiceOrderDto record = new AgedmallServiceOrderDto();
            record.setOrderSn(serviceorder.getServiceOrderId());
            record.setDepId(serviceorder.getDepId().longValue());
            record.setSubId(getOrderSn());//预约编号
            record.setUpdateTime(LocalDateTime.now());
            record.setHelptext(serviceorder.getHelpText());
            record.setWechatphone(serviceorder.getWechatPhone());
            record.setStat(OrderOperateType.WAITING_LIST);
            record.setUserId(serviceorder.getUserId());
            String subscribeTime[] = serviceorder.getSubTime().split("~");
            //预约开始完整时间
            String fullAppointTime = serviceorder.getSubDate()+" "+subscribeTime[0];
            //预约时间
            String appointmentTime = serviceorder.getSubDate();
            //预约开始时间
            String startTime = serviceorder.getSubDate() +" "+subscribeTime[0];
            //预约结束时间
            String endTime = serviceorder.getSubDate() + " "+subscribeTime[1];
            record.setFullAppointTime(fullAppointTime);
            record.setAppointmentTime(appointmentTime);
            record.setStartsTime(startTime);
            record.setEndTime(endTime);

            record.setDescribeImgs(StringUtils.join(serviceorder.getImages(),","));
            agedmallOnLineServiceOrderMapper.serviceCreateSub(record);


            //增加订单记录日志
            //saveOperateLog(serviceorder.getServiceOrderId(),OrderOperateType.ADD_SUBSCRIBE_ORDER);
            //根据预约编号查询在线服务自增id
            AgedmallServiceOrderExample example = new AgedmallServiceOrderExample();
            example.or().andSubidEqualTo(record.getSubId());
            AgedmallServiceOrder agedmallServiceOrder = agedmallServiceOrderMapper.selectOneByExample(example);
            if(agedmallServiceOrder != null){
                takeOrderService.sendToDoctorNotice(agedmallServiceOrder.getId());
            }
            this.saveServiceRecord(record.getSubId(),0);//0:表示待接单

            //增加医生抢单逻辑
            //根据科室id查询医生信息
            List<DoctorInfo> doctorInfoList = this.getagedmallDoctorInfo(serviceorder.getDepId().longValue());
            //将医生信息插入抢单表中
            record.setId(agedmallServiceOrder.getId());
            this.insertAgedmallTakeOrderRecord(doctorInfoList,record);

            return RespUtil.success();
        }catch (Exception e){
            return RespUtil.fail();
        }
    }

    /**
     * 增加抢单信息表
     * @param doctorInfoList
     * @param record
     */
    private void insertAgedmallTakeOrderRecord(List<DoctorInfo> doctorInfoList,AgedmallServiceOrderDto record){
        try {
            for(DoctorInfo dif : doctorInfoList){
                AgedmallTakeOrderRecord agedmallTakeOrderRecord = new AgedmallTakeOrderRecord();
                agedmallTakeOrderRecord.setPrintId(record.getId().intValue());
                agedmallTakeOrderRecord.setMessageType(4);//医生抢单
                //agedmallTakeOrderRecord.setDeliveryManId(Integer.parseInt(dif.getDoctorId()));
                agedmallTakeOrderRecord.setDeliveryManId(dif.getUserId());
                agedmallTakeOrderRecord.setState(0);//初始化
                agedmallTakeOrderRecord.setAddTime(LocalDateTime.now());
                agedmallTakeOrderRecord.setUpdateTime(LocalDateTime.now());
                agedmallTakeOrderRecord.setType(0);//顺序接单
                agedmallTakeOrderRecord.setTakeType(1);//在线服务来源数据
                agedmallTakeOrderRecord.setDepartmentId(record.getDepId().intValue());//科室id
                agedmallTakeOrderRecord.setSubid(record.getSubId());
                //agedmallTakeOrderRecord.setUserId(record.getUserId());
                agedmallTakeOrderRecordMapper.insertSelective(agedmallTakeOrderRecord);
            }
        }catch (Exception e){
           e.printStackTrace();
        }
    }

    private void saveServiceRecord(String subId,Integer recordType){
        //增加预约使用记录
        AgedmallOnlineServiceRecord agedmallOnlineServiceRecord  = new AgedmallOnlineServiceRecord();
        agedmallOnlineServiceRecord.setRecordNumber(subId);
        agedmallOnlineServiceRecord.setRecordType(recordType);
        agedmallOnlineServiceRecord.setCreateTime(LocalDateTime.now());
        agedmallOnlineServiceRecordMapper.insert(agedmallOnlineServiceRecord);
    }

    /**
     * 获取医生操作订单状态(将前端传过来的标识转换成数据库标识)
     * @param action
     * @return
     */
    private Integer getOrderStatus(String action){
        if(action.equals(OrderOperateType.REJECT)){
            return OrderOperateType.REJECT_6;
        }else if(action.equals(OrderOperateType.AGREE)){
            return OrderOperateType.AGREE_3;
        }else if(action.equals(OrderOperateType.BEGIN)){
            return OrderOperateType.BEGIN_4;
        }else if(action.equals(OrderOperateType.FINISH)){
            return OrderOperateType.FINISH_5;
        }
        return 0;
    }

    /**
     * 医生在线咨询服务-咨询服务预约订单操作（拒接、接单、开始服务、完成服务）
     * @param serviceorder
     * @return
     */
    public BaseResult doctorServiceOrderAction(Serviceorder serviceorder){
        try {
            //根据预约编号查询服务订单id
            AgedmallServiceOrderExample serviceOrderExample = new AgedmallServiceOrderExample();
            serviceOrderExample.or().andSubidEqualTo(serviceorder.getSubId());
            AgedmallServiceOrder agedmallServiceOrder = agedmallServiceOrderMapper.selectOneByExample(serviceOrderExample);
            if(agedmallServiceOrder.getAllot() != 1){
                AgedmallDoctorInfoExample agedmallDoctorInfoExample = new AgedmallDoctorInfoExample();
                agedmallDoctorInfoExample.or().andUserIdEqualTo(serviceorder.getUserId().longValue());
                AgedmallDoctorInfo adi = agedmallDoctorInfoMapper.selectOneByExample(agedmallDoctorInfoExample);
                if(adi != null){
                    Integer takeStatus = 0;
                    if(serviceorder.getAction().equals(OrderOperateType.REJECT)){
                        takeStatus = 2;
                    }
                    if(serviceorder.getAction().equals(OrderOperateType.AGREE)){
                        takeStatus = 3;
                    }
                    agedmallOnLineServiceOrderMapper
                            .updateAgedmallTakeOrderRecord(takeStatus.toString(),adi.getUserId().toString(),agedmallServiceOrder.getId().toString());
                }
            }

            Integer orderStatus = 0;
            if(serviceorder.getAction().equals(OrderOperateType.REJECT)){
                if(agedmallServiceOrder.getAllot() != 1) {
                    List<Integer> list = new ArrayList<>();
                    list.add(0);
                    list.add(3);
                    //根据预约编号查询是否存在0和3的数据，如果没有则说明已被全部拒绝
                    AgedmallTakeOrderRecordExample example = new AgedmallTakeOrderRecordExample();
                    example.or().andStateIn(list).andSubidEqualTo(serviceorder.getSubId());

                    List<AgedmallTakeOrderRecord> takeOrderRecordList = agedmallTakeOrderRecordMapper.selectByExample(example);
                    if (takeOrderRecordList.size() == 0) {
                        orderStatus = OrderOperateType.REJECT_6;
                    } else {
                        orderStatus = OrderOperateType.WAITING_LIST;
                    }
                }else {
                    orderStatus = OrderOperateType.REJECT_6;
                }
            }else if(serviceorder.getAction().equals(OrderOperateType.AGREE)){
                serviceorder.setAgreeTime(LocalDateTime.now());
                orderStatus = OrderOperateType.AGREE_3;
                this.saveServiceRecord(serviceorder.getSubId(),1);
            }else if(serviceorder.getAction().equals(OrderOperateType.BEGIN)){
                serviceorder.setStartTime(LocalDateTime.now());
                orderStatus = OrderOperateType.BEGIN_4;
                this.saveServiceRecord(serviceorder.getSubId(),2);
            }else if(serviceorder.getAction().equals(OrderOperateType.FINISH)){
                serviceorder.setFinishTime(LocalDateTime.now());
                orderStatus = OrderOperateType.FINISH_5;
                this.saveServiceRecord(serviceorder.getSubId(),3);
            }

            serviceorder.setOrderStatus(orderStatus);
            serviceorder.setDoctorId(serviceorder.getUserId());
            agedmallOnLineServiceOrderMapper.doctorServiceOrderAction(serviceorder);

            //Integer val = getOrderStatus(serviceorder.getAction());
            //增加订单记录日志
            //saveOperateLog(serviceorder.getSubId(),val);

            //修改用户抢单表数据状态 doctorId
            /*AgedmallTakeOrderRecordExample takeOrderRecordExample = new AgedmallTakeOrderRecordExample();
            takeOrderRecordExample.createCriteria().andDeliveryManIdEqualTo(serviceorder.getDoctorId());
            AgedmallTakeOrderRecord takeOrderRecord = new AgedmallTakeOrderRecord();
            takeOrderRecord.setState(3);//修改为接单成功
            agedmallTakeOrderRecordMapper.updateByExampleSelective(takeOrderRecord,takeOrderRecordExample);*/
            return RespUtil.success();
        }catch (Exception e){
            return RespUtil.fail();
        }
    }


    private String base64ToUrl(List<String> base64Img) {
        String path="app/serviceorder/";
        String realPath="";
        List<String> ossUrls=new ArrayList<>();
        try {
            if(SystemUtil.isWindows()){
                realPath=UploadConstant.WINDOS_BASE_UPLOAD_URL+path;
            }
            else if(SystemUtil.isMacOS()||SystemUtil.isMacOSX()){
                realPath=UploadConstant.MAC_BASE_UPLOAD_URL+path;
            }
            else{
                realPath=UploadConstant.LINUX_BASE_UPLOAD_URL+path;
            }
            for (int i = 0; i < base64Img.size(); i++) {
                String ossUrl="";

                String fileName="uploadLogistics-"+ IdUtil.fastSimpleUUID()+".jpg";
                FileUtil.mkdir(new File(realPath));
                String savePath=realPath+fileName;
                String ossPath=path+fileName;
                String isSave = Base64Util.generateImage(base64Img.get(i).substring(23), savePath);
                logger.info("图片保存错误：{}",isSave);
                logger.info("图片保存路径：{}",savePath);
                if(StrUtil.isNotBlank(isSave)){
                    return null;
                }
                OssUtil ossUtil=new OssUtil();
                //TODO 上传到oss
                ossUrl=ossUtil.uploadFile(savePath,ossPath);
                ossUrls.add(ossUrl);
            }
        }
        catch (Exception e){
            logger.error("图片转换失败：{}",e);
            return null;
        }

        return String.join(",",ossUrls);
    }


    /**
     * 获取订单操作内容
     * @param operateType 订单操作类型
     * @return 订单操作内容
     */
    public void saveOperateLog(String serviceOrderId, Integer operateType){
        String operateContent = null;
        if(OrderOperateType.CANCEL_ORDER.equals(operateType)) {
            operateContent = "取消预约订单，订单编号为：" + serviceOrderId;
        }else if(OrderOperateType.SUBSCRIBE_ORDER.equals(operateType)){
            operateContent = "修改预约订单，订单编号为：" + serviceOrderId;
        }else if(OrderOperateType.WAITING_LIST.equals(operateType)){
            operateContent = "医生待接单，订单编号为：" + serviceOrderId;
        }else if(OrderOperateType.AGREE_3.equals(operateType)){
            operateContent = "医生已接单，订单编号为：" + serviceOrderId;
        }else if(OrderOperateType.BEGIN_4.equals(operateType)){
            operateContent = "医生开始服务，订单编号为：" + serviceOrderId;
        }else if(OrderOperateType.FINISH_5.equals(operateType)){
            operateContent = "医生完成服务，订单编号为：" + serviceOrderId;
        }else if(OrderOperateType.REJECT_6.equals(operateType)){
            operateContent = "医生拒绝接单，订单编号为：" + serviceOrderId;
        }else{
            operateContent = "未知类型";
        }
        create(serviceOrderId, operateType, operateContent);
    }

    /**
     * 创建订单操作日志
     * @param operateType 订单操作类型
     * @param operateContent 订单操作内容
     * @return 订单操作日志
     * @throws Exception
     */
    private AgedmallOrderOperateLog create(String serviceOrderId,Integer operateType, String operateContent){
        AgedmallOrderOperateLog log = new AgedmallOrderOperateLog();
        log.setOrderInfoCode(serviceOrderId);
        log.setOperateType(operateType);
        log.setOperateContent(operateContent);
        log.setGmtCreate(LocalDateTime.now());
        log.setGmtModified(LocalDateTime.now());
        agedmallOrderOperateLogMapper.insert(log);
        return log;
    }


    /**
     * 用户在线咨询服务订单---获取在线咨询服务订单详情
     * @param serviceOrderParm
     * @return
     */
    public BaseResult serviceOrderDetail(ServiceOrderParm serviceOrderParm){
        List<ServiceOrderRetunDto> serviceOrderRetunDtoList
                = agedmallServiceOrderManageMapper.getServiceOrderListInfo(serviceOrderParm);
        OnLineServiceOrderVo onLineServiceOrderVo = null;
        for(ServiceOrderRetunDto sor : serviceOrderRetunDtoList){
            ServiceInfo serviceInfo = new ServiceInfo();
            //通过门点商品id查询门店店
            AgedmallStoreGoods agedmallStoreGoods = getStorId(sor.getStoreGoodsId());
            if(agedmallStoreGoods != null){
                //根据门店id查询
                StoreInfo storeInfo = getAgedmallStoreInfo(agedmallStoreGoods.getStoreId().intValue());//storeInfo
                serviceInfo.setStoreInfo(storeInfo);

                //根据商品id和门店id查询服务信息信息
                StoreGoodsVo goods = getStoreGoodsByGoodsId(sor.getGoodsId(), agedmallStoreGoods.getStoreId().intValue());
                //规格信息
                goods.setServiceId(sor.getServiceId());
                goods.setServicePrice(sor.getServicePrice());
                goods.setOriginalPrice(sor.getOriginalPrice());
                SkuDataInfo skuDataInfo = getSkuDataInfo(goods);//skuInfo
                serviceInfo.setSkuInfo(skuDataInfo);

                //服务信息
                GoodsBase goodsBase = getGoodsBase(sor);//goodsBase
                serviceInfo.setGoodsBase(goodsBase);

                //在线咨询服务扩展数据（数据结构和确认订单页面返回的extends数据结构一样）
                ServiceExtends serviceExtends = getServiceExtends(storeInfo.getId(),sor);//extend
                serviceInfo.setExtendsss(serviceExtends);


                //设置自己本身的属性值
               onLineServiceOrderVo = setOnLineServiceOrderVo(sor);
                onLineServiceOrderVo.setServiceInfo(serviceInfo);
                    SubInfo subInfo = getSubInfo(sor);
                    if(subInfo != null){
                        if(sor.getDoctorId() != null){
                            DoctorInfo doctorInfo =  getDoctorInfoById(Long.parseLong(sor.getDoctorId().toString()));
                            subInfo.setDoctorInfo(doctorInfo);
                        }
                        onLineServiceOrderVo.setSubInfo(subInfo);//subInfo
                    }
                    onLineServiceOrderVo.setOrderInfos(setOrderInfos(sor));
                    onLineServiceOrderVo.setUserAddress(setLitemallOrder(Integer.parseInt(sor.getOrderId())));
                }
        }
        return RespUtil.success(onLineServiceOrderVo);
    }

    /**
     * 根据订单编号,查询封装订单相关信息
     * @param sor
     * @return
     */
    private List<OrderInfos> setOrderInfos(ServiceOrderRetunDto sor){

        List<OrderInfos> orderInfosList = new ArrayList<>();
        //根据订单编号查询订单信息
        OrderInfos orderInfos = new OrderInfos();
        orderInfos.setName("在线服务订单");

        ServiceGroup serviceGroup1 = new ServiceGroup();
        serviceGroup1.setField("订单编号:");
        serviceGroup1.setValue(sor.getOrderSn());
        serviceGroup1.setCopy(0);

        ServiceGroup serviceGroup2 = new ServiceGroup();
        serviceGroup2.setField("服务名称:");
        serviceGroup2.setValue(sor.getServiceName());
        serviceGroup2.setCopy(0);

        ServiceGroup serviceGroup3 = new ServiceGroup();
        serviceGroup3.setField("服务日期:");
        serviceGroup3.setValue(sor.getStartTime());
        serviceGroup3.setCopy(0);

        List<ServiceGroup> serviceGroupList = new ArrayList<>();
        serviceGroupList.add(serviceGroup1);
        serviceGroupList.add(serviceGroup2);
        serviceGroupList.add(serviceGroup3);

        orderInfos.setList(serviceGroupList);
        orderInfosList.add(orderInfos);
        return orderInfosList;
    }

    /**
     * 前端-->后端状态转换
     * @param status
     * @return
     */
    private String statusBeforeConversion(Integer status){
        if(status == null){
            return null;
        }
       if(status == 0){//待接单
           return "2";
       }else if(status == 1){//待服务
           return "3";
       }else if(status == 2){//服务中
           return "4";
       }else if(status == 3){//已完成
           return "5";
       }
       return null;
    }

    /**
     * 后端-->前端状态转换
     * @param status
     * @return
     */
    private Integer statusAfterConversion(Integer status){
         if(status == 2){
             return 0;
         }else if(status == 3){
             return 1;
         }else if(status == 4 /*|| status == 3*/){
             return 2;
         }else if(status == 5 || status == 6){
             return 3;
         }
        return null;
    }


    /**
     * 获取当前可以抢单的医生id
     * @param departmentId
     * @return
     */
    private String getDoctorId(Long departmentId,Long userId){
        StringBuffer sb = new StringBuffer();
        List<String> stringList = new ArrayList<>();
        try {
            //        //通过科室id查询抢单表中的数据(查询state状态0的数据)
            //       /* AgedmallTakeOrderRecordExample example = new AgedmallTakeOrderRecordExample();
            //        example.or().andDepartmentIdEqualTo(departmentId.intValue());*/
            //       // List<AgedmallTakeOrderRecord> agedmallTakeOrderRecordList =  agedmallTakeOrderRecordMapper.selectByExample(example);
            //       // AgedmallTakeOrderRecord aor = null;
            //       // if(agedmallTakeOrderRecordList.size() >0){
            //
            //            //根据第一个医生id和科室id查询
            AgedmallTakeOrderRecordExample takeOrderRecordExample = new AgedmallTakeOrderRecordExample();
            takeOrderRecordExample.or()
                    .andDepartmentIdEqualTo(departmentId.intValue())
                    .andDeliveryManIdEqualTo(userId.intValue());
            List<AgedmallTakeOrderRecord> takeOrderRecordList =  agedmallTakeOrderRecordMapper.selectByExample(takeOrderRecordExample);
            for(AgedmallTakeOrderRecord ator : takeOrderRecordList){
                if((ator.getState() == 0) ){
                    //根据编号科室id查询是否存在状态为2的数据
                    AgedmallTakeOrderRecordExample recordExample = new AgedmallTakeOrderRecordExample();
                    recordExample.or()
                            .andSubidEqualTo(ator.getSubid())
                            .andDepartmentIdEqualTo(departmentId.intValue()).andStateEqualTo(0);
                    List<AgedmallTakeOrderRecord> recordList =  agedmallTakeOrderRecordMapper.selectByExample(recordExample);
                    if(recordList.size() >0){
                        for(AgedmallTakeOrderRecord orderRecord : recordList){
                            //取第一条数据
                            AgedmallTakeOrderRecord orderRecordOne = recordList.get(0);
                            //根据编号查询是否有3的状态,如果有3则不添加进来
                            AgedmallTakeOrderRecordExample recordExamples = new AgedmallTakeOrderRecordExample();
                            recordExamples.or()
                                    .andSubidEqualTo(ator.getSubid()).andStateEqualTo(3);
                            List<AgedmallTakeOrderRecord> recordListNum =  agedmallTakeOrderRecordMapper.selectByExample(recordExamples);
                            if(recordListNum.size() == 0){
                                if((orderRecord.getDeliveryManId() == userId.intValue()) && (orderRecordOne.getDeliveryManId() == userId.intValue()) ){
                                    stringList.add(orderRecord.getSubid());
                                }
                            }
                        }
                    }
                }

                if(ator.getState() == 3){
                    AgedmallTakeOrderRecordExample recordExample = new AgedmallTakeOrderRecordExample();
                    recordExample.or()
                            .andSubidEqualTo(ator.getSubid())
                            .andDepartmentIdEqualTo(departmentId.intValue()).andStateEqualTo(3);
                    List<AgedmallTakeOrderRecord> recordList =  agedmallTakeOrderRecordMapper.selectByExample(recordExample);
                    if(recordList.size() >0){
                        for(AgedmallTakeOrderRecord take: recordList){
                            if(take.getDeliveryManId() == userId.intValue()){
                                stringList.add(take.getSubid());
                            }
                        }
                    }
                }
            }
            for(String s :stringList){
                //根据编号查询，判断allot状态是否是1，如果是1,则不加入
                AgedmallServiceOrderExample serviceOrderExample = new AgedmallServiceOrderExample();
                serviceOrderExample.or().andSubidEqualTo(s);
                AgedmallServiceOrder agedmallServiceOrder = agedmallServiceOrderMapper.selectOneByExample(serviceOrderExample);
                if(agedmallServiceOrder != null){
                    if(agedmallServiceOrder.getAllot() != 1){
                        sb.append(s).append(",");
                    }
                }
            }
        }catch (Exception e){
          e.printStackTrace();
        }
        return sb.toString();
    }



    /**
     * 医生在线咨询服务-获取咨询服务预约订单列表
     * @param serviceOrderParm
     * @return
     */
    public BaseResult doctorServiceOrderList(ServiceOrderParm serviceOrderParm){
        try {
            //查询当前用户是否存在
            LitemallUser litemallUser = litemallUserMapper.selectByPrimaryKey(serviceOrderParm.getUserId());
            if(litemallUser == null){
                return RespUtil.fail(6001,"用户不存在！");
            }

            //当前登录用户id和是否是合台分配的状态进行查询
            AgedmallServiceOrderExample serviceOrderExample = new AgedmallServiceOrderExample();
            serviceOrderExample.or()
                    .andDoctorIdEqualTo(serviceOrderParm.getUserId().longValue())
                    .andAllotEqualTo(1)//表示是后台分配的，不参与顺序接单
                    .andStatNotEqualTo(6);
            List<AgedmallServiceOrder> agedmallServiceOrderList = agedmallServiceOrderMapper.selectByExample(serviceOrderExample);

            //根据当前登录用户id查询医生所属的科室
            AgedmallDoctorInfoExample example = new AgedmallDoctorInfoExample();
            example.or().andUserIdEqualTo(serviceOrderParm.getUserId().longValue());
            AgedmallDoctorInfo agedmallDoctorInfo = agedmallDoctorInfoMapper.selectOneByExample(example);
            if(agedmallDoctorInfo == null){
                return RespUtil.fail(6002,"科室不存在！");
            }
            serviceOrderParm.setDepartementId(agedmallDoctorInfo.getDepartmentId());
            List<OnLineServiceOrderVo> onLineServiceOrderVoList = new ArrayList<>(50);
            String ordrStatus = statusBeforeConversion(serviceOrderParm.getStatus());
            serviceOrderParm.setOrderStatus(ordrStatus);
            //获取医生id
            String sb = this.getDoctorId(agedmallDoctorInfo.getDepartmentId(),serviceOrderParm.getUserId().longValue());
            if((sb == "" || sb.equals("")) && agedmallServiceOrderList.size() == 0){
                PageData<OnLineServiceOrderVo> pageData = new PageData<>();
                return RespUtil.success(pageData);
            }
            if(!sb.equals("")){
                String subId = sb.substring(0,sb.length()-1);
                serviceOrderParm.setGrabSingleNumber(subId);
            }
            List<ServiceOrderRetunDto>  serviceOrderRetunDtoList
                        = agedmallServiceOrderService.getServiceDoctoryOrderListInfo(serviceOrderParm);
            PageInfo<ServiceOrderRetunDto> pagedList = PageInfo.of(serviceOrderRetunDtoList);

            if(serviceOrderRetunDtoList.size() > 0){
                for(ServiceOrderRetunDto sor : serviceOrderRetunDtoList){
                    ServiceInfo serviceInfo = new ServiceInfo();
                    //通过门点商品id查询门店店
                    AgedmallStoreGoods agedmallStoreGoods = getStorId(sor.getStoreGoodsId());
                    if(agedmallStoreGoods != null){
                        //根据门店id查询
                        StoreInfo storeInfo = getAgedmallStoreInfo(agedmallStoreGoods.getStoreId().intValue());//storeInfo
                        serviceInfo.setStoreInfo(storeInfo);

                        //根据商品id和门店id查询服务信息信息
                        StoreGoodsVo goods = getStoreGoodsByGoodsId(sor.getGoodsId(), agedmallStoreGoods.getStoreId().intValue());
                        //规格信息
                        goods.setServiceId(sor.getServiceId());
                        goods.setServicePrice(sor.getServicePrice());
                        goods.setOriginalPrice(sor.getOriginalPrice());
                        SkuDataInfo skuDataInfo = getSkuDataInfo(goods);//skuInfo
                        serviceInfo.setSkuInfo(skuDataInfo);

                        //服务信息
                        GoodsBase goodsBase = getGoodsBase(sor);//goodsBase
                        serviceInfo.setGoodsBase(goodsBase);

                        //在线咨询服务扩展数据（数据结构和确认订单页面返回的extends数据结构一样）
                        ServiceExtends serviceExtends = getServiceExtends(storeInfo.getId(),sor);//extend
                        serviceInfo.setExtendsss(serviceExtends);


                        //设置自己本身的属性值
                        OnLineServiceOrderVo onLineServiceOrderVo = new OnLineServiceOrderVo();// setOnLineServiceOrderVo(sor);
                        onLineServiceOrderVo.setServiceOrderId(sor.getOrderSn());
                        onLineServiceOrderVo.setServiceInfo(serviceInfo);
                        SubInfo subInfo = getSubInfo(sor);
                            if(subInfo != null){
                                if(sor.getDoctorId() != null){
                                    DoctorInfo doctorInfo =  getDoctorInfoById(Long.parseLong(sor.getDoctorId().toString()));
                                    subInfo.setDoctorInfo(doctorInfo);
                                }
                                subInfo.setUserAddress(setLitemallOrder(Integer.parseInt(sor.getOrderId())));
                                onLineServiceOrderVo.setSubInfo(subInfo);//subInfo
                            }
                        onLineServiceOrderVoList.add(onLineServiceOrderVo);
                    }

                }
            }
            PageData<OnLineServiceOrderVo> pageData = new PageData<>();
            pageData.setNowPage(serviceOrderParm.getPage());
            pageData.setTotalPage(pagedList.getPages());
            pageData.setTotalRows((int) pagedList.getTotal());
            pageData.setRows(onLineServiceOrderVoList);
            return RespUtil.success(pageData);
        }catch (Exception e){
            return RespUtil.fail();
        }
    }

    private String setOrderStatus(String orderStatus){
        String  stat = null;
        if(orderStatus.equals("100")){//待支付
            stat = "0";
        }else if(orderStatus.equals("200")){//待使用
            stat = "1";
        }else if(orderStatus.equals("300")){//预约中
            stat = "2";
        }else if(orderStatus.equals("400")){//服务中
            stat = "3,4";
        }else if(orderStatus.equals("500,600")){//已完成 /已关闭
            stat = "5,7";
        }
        return stat;
    }


    /**
     * 用户在线咨询服务订单---用户操作---使用记录
     * @param serviceOrderParm
     * @return
     */
    public BaseResult serviceRecordList(ServiceOrderParm serviceOrderParm){
        List<ServiceOrderRetunDto> serviceOrderRetunDtoList
                = agedmallServiceOrderManageMapper.getServiceOrderHistoryListInfo(serviceOrderParm);
        List<OnLineServiceOrderVo> onLineServiceOrderVoList = new ArrayList<>(50);
        for(ServiceOrderRetunDto sor : serviceOrderRetunDtoList){
            ServiceInfo serviceInfo = new ServiceInfo();
            //通过门点商品id查询门店店
            AgedmallStoreGoods agedmallStoreGoods = getStorId(sor.getStoreGoodsId());
            if(agedmallStoreGoods != null){
                //根据门店id查询
                StoreInfo storeInfo = getAgedmallStoreInfo(agedmallStoreGoods.getStoreId().intValue());//storeInfo
                serviceInfo.setStoreInfo(storeInfo);
                //根据商品id和门店id查询服务信息信息
                StoreGoodsVo goods = getStoreGoodsByGoodsId(sor.getGoodsId(), agedmallStoreGoods.getStoreId().intValue());
                //服务信息
                GoodsBase goodsBase = getGoodsBase(sor);//goodsBase
                serviceInfo.setGoodsBase(goodsBase);
                //规格信息
                goods.setServiceId(sor.getServiceId());
                goods.setServicePrice(sor.getServicePrice());
                goods.setOriginalPrice(sor.getOriginalPrice());
                SkuDataInfo skuDataInfo = getSkuDataInfo(goods);//skuInfo
                serviceInfo.setSkuInfo(skuDataInfo);
                //在线咨询服务扩展数据（数据结构和确认订单页面返回的extends数据结构一样）
                ServiceExtends serviceExtends = getServiceExtends(storeInfo.getId(),sor);//extend
                serviceInfo.setExtendsss(serviceExtends);
                //设置自己本身的属性值
                OnLineServiceOrderVo onLineServiceOrderVo = setOnLineServiceOrderVo(sor);
                onLineServiceOrderVo.setServiceInfo(serviceInfo);
                sor.setHistorType("his");
                SubInfo subInfo =  getSubInfo(sor);
                if(subInfo != null){
                    if(sor.getDoctorId() != null){
                        DoctorInfo doctorInfo =  getDoctorInfoById(Long.parseLong(sor.getDoctorId().toString()));
                        subInfo.setDoctorInfo(doctorInfo);
                    }
                    onLineServiceOrderVo.setSubInfo(subInfo);//subInfo
                }
                onLineServiceOrderVoList.add(onLineServiceOrderVo);
            }
        }
       if(onLineServiceOrderVoList.size() > 0){
           if(onLineServiceOrderVoList.get(0).getSubInfo() != null){
               return RespUtil.success(onLineServiceOrderVoList);
           }
       }
        return RespUtil.success(null);//待修改
    }



    /**
     *用户在线咨询服务订单---获取在线咨询服务订单列表数据
     * @return
     */
    public BaseResult serviceOrderList(ServiceOrderParm serviceOrderParm){
       try {
           List<OnLineServiceOrderVo> onLineServiceOrderVoList = new ArrayList<>(50);
           String orderStatus = null;
           if(serviceOrderParm.getOrderStatus() != null){
               orderStatus = this.setOrderStatus(serviceOrderParm.getOrderStatus());
           }
           serviceOrderParm.setOrderStatus(orderStatus);
           List<ServiceOrderRetunDto> serviceOrderRetunDtoList
                   = agedmallServiceOrderService.getServiceOrderListInfo(serviceOrderParm);

           PageInfo<ServiceOrderRetunDto> pagedList = PageInfo.of(serviceOrderRetunDtoList);

           if(serviceOrderRetunDtoList.size() >0){
               for(ServiceOrderRetunDto sor : serviceOrderRetunDtoList){
                   ServiceInfo serviceInfo = new ServiceInfo();
                   //通过门点商品id查询门店店
                   AgedmallStoreGoods agedmallStoreGoods = getStorId(sor.getStoreGoodsId());
                   if(agedmallStoreGoods != null){
                       //根据门店id查询
                       StoreInfo storeInfo = getAgedmallStoreInfo(agedmallStoreGoods.getStoreId().intValue());//storeInfo
                       serviceInfo.setStoreInfo(storeInfo);
                       //根据商品id和门店id查询服务信息信息
                       StoreGoodsVo goods = getStoreGoodsByGoodsId(sor.getGoodsId(), agedmallStoreGoods.getStoreId().intValue());
                       //规格信息
                       goods.setServiceId(sor.getServiceId());
                       goods.setServicePrice(sor.getServicePrice());
                       goods.setOriginalPrice(sor.getOriginalPrice());
                       SkuDataInfo skuDataInfo = getSkuDataInfo(goods);//skuInfo
                       serviceInfo.setSkuInfo(skuDataInfo);
                       //服务信息
                      GoodsBase goodsBase = getGoodsBase(sor);//goodsBase
                      serviceInfo.setGoodsBase(goodsBase);
                       //在线咨询服务扩展数据（数据结构和确认订单页面返回的extends数据结构一样）
                       ServiceExtends serviceExtends = getServiceExtends(storeInfo.getId(),sor);//extend
                       serviceInfo.setExtendsss(serviceExtends);

                       //设置自己本身的属性值
                       OnLineServiceOrderVo onLineServiceOrderVo = setOnLineServiceOrderVo(sor);
                       onLineServiceOrderVo.setServiceInfo(serviceInfo);
                       SubInfo subInfo = getSubInfo(sor);
                       if(subInfo != null){
                           if(sor.getDoctorId() != null){
                               DoctorInfo doctorInfo =  getDoctorInfoById(Long.parseLong(sor.getDoctorId().toString()));
                               subInfo.setDoctorInfo(doctorInfo);
                           }
                           onLineServiceOrderVo.setSubInfo(subInfo);//subInfo
                           onLineServiceOrderVo.setOrderInfos(setOrderInfos(sor));
                           onLineServiceOrderVo.setUserAddress(setLitemallOrder(Integer.parseInt(sor.getOrderId())));
                       }
                       onLineServiceOrderVoList.add(onLineServiceOrderVo);
                   }
               }
           }
           PageData<OnLineServiceOrderVo> pageData = new PageData<>();
           pageData.setNowPage(serviceOrderParm.getPage());
           pageData.setTotalPage(pagedList.getPages());
           pageData.setTotalRows((int) pagedList.getTotal());
           pageData.setRows(onLineServiceOrderVoList);
           return RespUtil.success(pageData);
       }catch (Exception e){
           return RespUtil.fail();
       }
    }

    /**
     * 根据订单编号查询预约中和服务中的数据
     * @return
     */
    private SubInfo getSubInfo(ServiceOrderRetunDto sor){
        SubInfo subInfo = null;
        SubInfoReturnDto subInfoReturnDto =  agedmallServiceOrderManageMapper.getServiceOrderApplyInfo(sor.getOrderSn());
        if(subInfoReturnDto != null){
            subInfo = new SubInfo();
            subInfo.setSubId(subInfoReturnDto.getSubId());
            subInfo.setSubDate(subInfoReturnDto.getSubDate());
            subInfo.setSubTime(subInfoReturnDto.getStartsTime()+"~"+subInfoReturnDto.getEndTime());
            if(sor.getHistorType() != null){
                subInfo.setStatus(sor.getStat());
                subInfo.setSubmitTime(sor.getSubmitTime());//预约时间
            }else{
                Integer statusAfter = this.statusAfterConversion(subInfoReturnDto.getStatus());
                subInfo.setStatus(statusAfter);
               subInfo.setSubmitTime(subInfoReturnDto.getSubDate()+" "+subInfoReturnDto.getStartsTime());//预约时间
            }
            subInfo.setDepId(subInfoReturnDto.getDepId());
            subInfo.setDepName(subInfoReturnDto.getDepName());
            subInfo.setWechatPhone(subInfoReturnDto.getWechatPhone());
            subInfo.setHelpText(subInfoReturnDto.getHelpText());
            if(subInfoReturnDto.getImages() != null){
                String imageUrls[] = subInfoReturnDto.getImages().split(",");
                List<String> listImage = new ArrayList<>();
                for(String image : imageUrls){
                    listImage.add(image);
                }
                subInfo.setImages(listImage);
            }
            subInfo.setStartTime(subInfoReturnDto.getStartTime());
            subInfo.setAgreeTime(subInfoReturnDto.getAgreeTime());
            subInfo.setFinishTime(subInfoReturnDto.getFinishTime());
            return subInfo;
        }
        return null;
    }




    /**
     * 根据大订单id，查询大订单信息，获取相关地址信息
     * @param orderId
     */
    private UserAddress setLitemallOrder(Integer orderId){
        UserAddress userAddress = null;
        LitemallOrder litemallOrder = litemallOrderMapper.selectByPrimaryKey(orderId);
        if(litemallOrder != null ){
            userAddress = new UserAddress();
            userAddress.setProvince(litemallOrder.getProvince());
            userAddress.setCity(litemallOrder.getCity());
            userAddress.setHosId(litemallOrder.getHospitalId());
            userAddress.setHosName(litemallOrder.getHospitalName());
            userAddress.setLat(litemallOrder.getLat());
            userAddress.setLng(litemallOrder.getLng());
            userAddress.setVillage(litemallOrder.getCounty());
            userAddress.setUserName(litemallOrder.getConsignee());
            // userAddress.setGender(litemallOrder.);//收货人性别
            userAddress.setPhone(litemallOrder.getMobile());
            userAddress.setIsDefault("1");//是否是默认收货
            userAddress.setAddress(litemallOrder.getAddress());
            userAddress.setDetail(litemallOrder.getAddressDetail());
            //isHos
            //userAddress.setIsHos(litemallOrder.get);//是否是医院小时达收货地址
            return userAddress;
        }
        return null;
    }


    /**
     *  根据科室id查询医生信息
     * @param doctorId
     * @return
     */
    private DoctorInfo getDoctorInfoById(Long doctorId){
        DoctorInfo doctorInfo = null;
        LitemallUser litemallUser = getLitemallUser(doctorId);
        if(litemallUser != null){
            AgedmallDoctorInfoExample example = new AgedmallDoctorInfoExample();
            example.or().andDeletedEqualTo(false)
                    .andUserIdEqualTo(doctorId);
            AgedmallDoctorInfo agedmallDoctorInfo = agedmallDoctorInfoMapper.selectOneByExample(example);
            if(agedmallDoctorInfo != null){
                doctorInfo = new DoctorInfo();
                doctorInfo.setDoctorId(agedmallDoctorInfo.getId().toString());
                doctorInfo.setDoctorName(agedmallDoctorInfo.getDoctorName());
                doctorInfo.setDoctorAvatar(litemallUser.getAvatar());
                //根据用户id查询
                doctorInfo.setHospital(agedmallDoctorInfo.getHospitalName());
            }
        }
        return doctorInfo;
    }


    /**
     * 设置流转状态
     * @param sor
     * @return
     */
    private OnLineServiceOrderVo setOnLineServiceOrderVo(ServiceOrderRetunDto sor){
        //设置自己本身的信息
        OnLineServiceOrderVo onLineServiceOrderVo = new OnLineServiceOrderVo();
        onLineServiceOrderVo.setServiceOrderId(sor.getOrderSn());
        //状态(0-待付款 1-待预约  2-待接单 3-接单  4-开始服务  5-完成服务  6-拒接单)
        if(sor.getStat() == 0){//待付款
            onLineServiceOrderVo.setServiceOrderStatus(100);
            onLineServiceOrderVo.setResidueCount(1);//设置为0次
        }
        if(sor.getStat() == 1){//待预约
            onLineServiceOrderVo.setResidueCount(1);//设置为1次
            onLineServiceOrderVo.setServiceOrderStatus(200);
        }
        if(sor.getStat() == 2){//待接单
            onLineServiceOrderVo.setResidueCount(0);//设置为1次
            onLineServiceOrderVo.setServiceOrderStatus(300);
        }
        if(sor.getStat() == 3 || sor.getStat() == 4){//服务中
            onLineServiceOrderVo.setResidueCount(0);//设置为1次
            onLineServiceOrderVo.setServiceOrderStatus(400);//设置为次
        }
        if(sor.getStat() == 5){
            onLineServiceOrderVo.setResidueCount(0);//设置为1次
            onLineServiceOrderVo.setServiceOrderStatus(500);//设置为次
        }
        if(sor.getStat() == 6 || sor.getStat() == 7){
            if(sor.getStat() == 6){
                onLineServiceOrderVo.setResidueCount(0);//设置为1次
            }else{
                onLineServiceOrderVo.setResidueCount(1);//设置为1次
            }
            onLineServiceOrderVo.setServiceOrderStatus(600);//设置为次
        }
        onLineServiceOrderVo.setServiceOrderPrice(sor.getServicePrice());
        if(sor.getStat() != 0){
            onLineServiceOrderVo.setIsPay(1);
        }else {
            onLineServiceOrderVo.setIsPay(0);
        }
        onLineServiceOrderVo.setIsAlonePay(0);
       // LitemallOrder litemallOrder = litemallOrderMapper.selectByPrimaryKey(Integer.parseInt(sor.getOrderId()));
        onLineServiceOrderVo.setBigOrderId(sor.getOrderId());

        return onLineServiceOrderVo;

    }


    /**
     * 根据门店商品id查询门店id
     * @param storeGoodId
     * @return
     */
    private AgedmallStoreGoods getStorId(Long storeGoodId){
        AgedmallStoreGoods agedmallStoreGoods = agedmallStoreGoodsMapper.selectByPrimaryKey(storeGoodId);
        return agedmallStoreGoods;
    }


    /**
     * 门店自增id
     * @param busId
     * @return
     */
    private ServiceExtends getServiceExtends(Long busId,ServiceOrderRetunDto sor){
        ServiceExtends serviceExtends = new ServiceExtends();
        List<DepartmentInfo> departmentInfoList = getAgedmallDepartmentInfo(busId);
        serviceExtends.setDepartmentList(departmentInfoList);
        //根据在线咨询服务订单编号查询预约天数和时间段
        serviceExtends.setSubtime(setSubTime(sor));
        return serviceExtends;
    }

    /**
     * 设置subTime(根据在线服务id查询)
     * @return
     */
    private Subtime setSubTime(ServiceOrderRetunDto sor){
        Subtime subtime = null;
        if(sor.getServiceId() != null){
            subtime = new Subtime();
            //预约最大天数
            Integer maxDay = sor.getAppointmentDay();
            subtime.setMaxDay(maxDay.toString());
            //预约时间段
            List<MakeTime> makeTimeList = JSON.parseArray(sor.getServiceTime(), MakeTime.class);
            List<SubTimeInfo> subTimeInfoList = new ArrayList<>();
            for(MakeTime mt : makeTimeList){
                SubTimeInfo subTimeInfo =new SubTimeInfo();
                subTimeInfo.setStime(mt.getStartTime());
                subTimeInfo.setEtime(mt.getEndTime());
                subTimeInfoList.add(subTimeInfo);
            }
            subtime.setTimeList(subTimeInfoList);
        }
        return subtime;
    }


    /**
     * 查询所有的科室
     * @param busId
     * @return
     */
    private List<DepartmentInfo> getAgedmallDepartmentInfo(Long busId){
      /*  AgedmallDepartmentExample agedmallDepartmentExample = new AgedmallDepartmentExample();
        agedmallDepartmentExample.or().andDeletedEqualTo(false);
        List<AgedmallDepartment> agedmallDepartmentList = agedmallDepartmentMapper.selectByExample(agedmallDepartmentExample);*/
      //查询所有的科室信息
      List<AgedmallServiceDepartment>  agedmallDepartmentList = agedmallServiceDepartmentMapper.getDepartment();
        //List<DepartmentInfo> setDepartMentInfo = setDepartMentInfo(agedmallDepartmentList);
        List<DepartmentInfo> departmentInfoList = new ArrayList<>(agedmallDepartmentList.size());

        for(AgedmallServiceDepartment ad : agedmallDepartmentList){
            DepartmentInfo departmentInfo = new DepartmentInfo();
            departmentInfo.setDepId(ad.getId());
            departmentInfo.setDepName(ad.getName());
            departmentInfoList.add(departmentInfo);
            List<DoctorInfo> doctorInfoList = this.getagedmallDoctorInfo(ad.getId().longValue());
           // List<DoctorInfo> doctorInfoList = null;
           /* if(agedmallDepartmentList.size() >0 || agedmallDepartmentList != null){
                doctorInfoList =  new ArrayList<>();
                for(AgedmallServiceDoctorInfo doc: agedmallDoctorInfoList){
                    LitemallUser litemallUser = getLitemallUser(doc.getUserId());//ad.getUserId()
                    DoctorInfo doctorInfo = null;
                    if(litemallUser != null){
                        doctorInfo = new DoctorInfo();
                        doctorInfo.setDoctorId(doc.getDoctorId().toString());
                        doctorInfo.setDoctorName(doc.getDoctorName());
                        doctorInfo.setDoctorAvatar(litemallUser.getAvatar());
                        doctorInfo.setHospital(doc.getHospitalName());
                        doctorInfoList.add(doctorInfo);
                    }
                }
            }*/
                 if(doctorInfoList != null){
                     departmentInfo.setDoctorList(doctorInfoList);
                 }
            //departmentInfo.setDoctorList();
            //departmentInfoList.add(departmentInfo);
        }
        return departmentInfoList;
    }

    /**
     * 根据科室id查询医生信息
     * @param departmentId
     * @return
     */
    private List<AgedmallDoctorInfo> getAgedmallDoctorInfo(Long departmentId){
       AgedmallDoctorInfoExample example = new AgedmallDoctorInfoExample();
       example.or().andDepartmentIdEqualTo(departmentId)
                   .andDeletedEqualTo(false);
       List<AgedmallDoctorInfo> agedmallDoctorInfoList = agedmallDoctorInfoMapper.selectByExample(example);
        return agedmallDoctorInfoList;
    }


    /**
     * 将部门封装到departementInfo对象中
     * @param agedmallDepartmentList
     * @return
     */
    private List<DepartmentInfo> setDepartMentInfo(List<AgedmallDepartment> agedmallDepartmentList){
        List<DepartmentInfo> departmentInfoList = new ArrayList<>(agedmallDepartmentList.size());
        for(AgedmallDepartment ad : agedmallDepartmentList){
            DepartmentInfo departmentInfo = new DepartmentInfo();
            departmentInfo.setDepId(ad.getId());
            departmentInfo.setDepName(ad.getName());
            departmentInfoList.add(departmentInfo);

            //List<DoctorInfo> doctorInfoList = getagedmallDoctorInfo(departmentInfo.getDepId().longValue());

           // departmentInfo.setDoctorList(doctorInfoList);
        }
        return departmentInfoList;
    }

    /**
     * 根据科室id查询医生信息
     * @param departmentId
     * @return
     */
    private List<DoctorInfo> getagedmallDoctorInfo(Long departmentId){
        AgedmallDoctorInfoExample example = new AgedmallDoctorInfoExample();
        example.or().andDepartmentIdEqualTo(departmentId)
                    .andDeletedEqualTo(false);
        List<AgedmallDoctorInfo> agedmallDoctorInfoList = agedmallDoctorInfoMapper.selectByExample(example);
        if(agedmallDoctorInfoList.size() > 0){
            List<DoctorInfo> doctorInfoList = new ArrayList<>();
            for(AgedmallDoctorInfo ad : agedmallDoctorInfoList){
                DoctorInfo doctorInfo = null;
                //根据用户userid查询litemall_user表信息
                LitemallUser litemallUser = getLitemallUser(ad.getUserId());//ad.getUserId()
                if(litemallUser != null){
                    doctorInfo = new DoctorInfo();
                    doctorInfo.setDoctorId(ad.getId().toString());
                    doctorInfo.setDoctorName(ad.getDoctorName());
                    doctorInfo.setDoctorAvatar(litemallUser.getAvatar());
                    doctorInfo.setHospital(ad.getHospitalName());
                    doctorInfo.setUserId(ad.getUserId().intValue());
                    doctorInfoList.add(doctorInfo);
                }
            }
            return doctorInfoList;
        }
        return null;
    }
    /**
     * 据用户userid查询litemall_user表信息
     * @param userId
     * @return
     */
    private LitemallUser getLitemallUser(Long userId){
        LitemallUserExample example = new LitemallUserExample();
        byte STATUS_NORMAL = 0;//用户状态
        example.or().andIdEqualTo(userId.intValue())
                .andDeletedEqualTo(false)
                .andStatusEqualTo(STATUS_NORMAL);
        LitemallUser litemallUser = litemallUserMapper.selectOneByExample(example);
        return litemallUser;
    }


    /**
     * 根据门店id
     * @param id
     * @return
     */
    private StoreInfo getAgedmallStoreInfo(Integer id){
        StoreInfo storeInfo = new StoreInfo();
        //根据门店id查询门店信息
        AgedmallStore agedmallStore = agedmallStoreService.findStoreById(id);
        storeInfo.setId(agedmallStore.getId());
        storeInfo.setName(agedmallStore.getStoreName());
        storeInfo.setLogo(agedmallStore.getLogo());
        storeInfo.setStarScore(agedmallStore.getStarScore().longValue());
        storeInfo.setTelPhone(agedmallStore.getPhone());
        storeInfo.setIsSelf(agedmallStore.getOwnOptFlg().intValue());
        //获取门店下的租赁数量
        int saleGoodsCount = countByStoreId(agedmallStore.getId().intValue(), GoodsConstant.GOODS_TYPE_SALE);
        int leaseGoodsCount = countByStoreId(agedmallStore.getId().intValue(), GoodsConstant.GOODS_TYPE_LEASE);
        storeInfo.setLeaseGoodsCount(leaseGoodsCount);
        storeInfo.setSaleGoodsCount(saleGoodsCount);
        return storeInfo;
    }

    /**
     * 获取门店下指定类型商品数
     * @param storeId
     * @param goodsType
     * @return
     */
    private int countByStoreId(Integer storeId, String goodsType) {
        return appGoodsMapper.getCountByStoreId(storeId, goodsType);
    }

    /**
     * 根据商品id和门店id查询
     * @param goodsId
     * @param storeId
     * @return
     */
    private StoreGoodsVo getStoreGoodsByGoodsId(Integer goodsId, Integer storeId) {
        return appGoodsMapper.getStoreGoodsByGoodsId(goodsId, storeId);
    }


    /**
     * 根据服务订单编号查询用户已下单的服务
     * @param sor
     * @return
     */
    private GoodsBase getGoodsBase(ServiceOrderRetunDto sor) {
        //封装服务基本信息
        GoodsBase goodsBase = new GoodsBase();
       try {
           if (null == sor) {
               return null;
           }
           /*AgedmallServiceOrderExample example = new AgedmallServiceOrderExample();
           example.or().andOrderSnEqualTo(sor.getOrderSn())
                   .andDeletedEqualTo(false);*/
           // AgedmallServiceOrder agedmallServiceOrder = agedmallServiceOrderMapper.selectOneByExample(example);
           //查询服务信息
           //AgedmallOnlineService agedmallOnlineService = getAgedmallOnlineServiceInfo(agedmallServiceOrder.getServiceId());
           goodsBase.setId(sor.getServiceId().longValue());
           if(sor.getServiceName() != null){
               goodsBase.setName(sor.getServiceName());
           }
           String serviceUrls = sor.getServiceImage();
           if (org.apache.commons.lang3.StringUtils.isNotEmpty(serviceUrls)) {
               List<String> urlList = JSONObject.parseArray(serviceUrls, String.class);
               goodsBase.setMainImage(CollectionUtils.isNotEmpty(urlList) ? urlList.get(0) : null);
           }
           goodsBase.setType("service");
           Integer serviceGoods = 0;
           if(sor.getServiceStatus() ==1){
               serviceGoods = 1;
           }
           goodsBase.setIsOffline(serviceGoods);
           List<Tags> tagsList = this.getListTags(sor.getTagId());
           goodsBase.setTags(tagsList);
           //封装在线服务价格价格
           goodsBase.setPriceInfo(this.setPriceInfo(sor));
       }catch (Exception e){
        e.printStackTrace();
       }
        return goodsBase;
    }


    /**
     * 设置在线服务价格
     * @param sor
     * @return
     */
    private PriceInfo setPriceInfo(ServiceOrderRetunDto sor){
        //通过在线服务id查询在线服务订单表信息
        AgedmallServiceOrderExample example = new AgedmallServiceOrderExample();
        example.or().andServiceIdEqualTo(sor.getId())
                    .andDeletedEqualTo(false);
      //  AgedmallServiceOrder agedmallServiceOrder = agedmallServiceOrderMapper.selectOneByExample(example);
        PriceInfo priceInfo = new PriceInfo();
        priceInfo.setLinePrice(sor.getOriginalPrice());
        priceInfo.setPrice(sor.getServicePrice());
        priceInfo.setSuffix("次");
        return priceInfo;
    }

    /**
     * 根据在线服务中的tags_id查询标签信息
     * @param tagId
     * @return
     */
    private List<Tags> getListTags(String tagId){
        List<Tags> tagsList = new ArrayList<>();
        //解析tagId字符数组
        String tags[] = tagId.split(",");
        for (String s : tags){
            //根据标签id到标签表中查询
            AgedmallTags tagsInfo = getTags(Integer.parseInt(s));
            Tags t = new Tags();
            t.setTagId(tagsInfo.getId());
            t.setTag(tagsInfo.getName());
            t.setIsRed(tagsInfo.getProminent());
            tagsList.add(t);
        }
        return tagsList;
    }

    /**
     * 根据主键查询
     * @param tagId
     * @return
     */
    private AgedmallTags getTags(Integer tagId){
        AgedmallTags agedmallTags = agedmallTagsMapper.selectByPrimaryKey(tagId.longValue());
        return agedmallTags;
    }

    /**
     * 根据服务订单表中的服务规格id到服务规格表中查询服务信息
     * @param serviceProductId
     * @return
     */
    private String getServiceType(Integer serviceProductId){
        String serviceType = null;
        AgedmallOnlineServiceProduct agedmallOnlineServiceProduct
                = agedmallOnlineServiceProductMapper.selectByPrimaryKey(serviceProductId);
        if(agedmallOnlineServiceProduct != null){
            List<ServiceSpec> specifications =
                    JSON.parseArray("["+agedmallOnlineServiceProduct.getSpecifications()+"]", ServiceSpec.class);
            for(ServiceSpec ls : specifications){
                List<Regualrs> regualrsList = ls.getRegualrs();
                for(Regualrs rg : regualrsList){
                    serviceType = rg.getValue();
                }
            }
        }
        return serviceType;
    }

    /**
     * 根据服务id查询服务信息
     * @return
     */
    private AgedmallOnlineService getAgedmallOnlineServiceInfo(Integer serverId){
        AgedmallOnlineService agedmallOnlineService =agedmallOnlineServiceMapper.selectByPrimaryKey(serverId);
        return agedmallOnlineService;
    }

    /**
     * 查询规格信息
     * @return
     */
    private SkuDataInfo getSkuDataInfo(StoreGoodsVo goods){
        SkuDataInfo skuInfo = new SkuDataInfo();
        GoodsDataSku goodsSku = getSkuItemList(goods);
        skuInfo.setGoodsSku(goodsSku);
        skuInfo.setSelectedGoodsSpec(getLitemallGoodsProduct(goods));

        return skuInfo;
    }

    /**
     * 查询商品和规格中间表a
     * @param goods
     * @return
     */
    private SelectedGoodsSpecInfo getLitemallGoodsProduct(StoreGoodsVo goods){
        //根据服务id和服务类型type,查询litemall_goods_product信息表
        LitemallGoodsProductExample example = new LitemallGoodsProductExample();
        example.or().andGoodsIdEqualTo(goods.getServiceId())
                    .andTypeEqualTo(AgedmallGoodsSpecificationInfoConstant.TYPE_ONINE)
                    .andDeletedEqualTo(false);
        LitemallGoodsProduct litemallGoodsProduct = litemallGoodsProductMapper.selectOneByExample(example);;

        SelectedGoodsSpecInfo selectedGoodsSpecInfo = new SelectedGoodsSpecInfo(); //this.getSelectGoosInfo(litemallGoodsProduct);
        selectedGoodsSpecInfo.setId(litemallGoodsProduct.getId());
        selectedGoodsSpecInfo.setStock(1);
        return selectedGoodsSpecInfo;
    }

    /**
     *  封装用户选择selectedGoodsSpec
     * @param litemallGoodsProduct
     * @return
     */
    private SelectedGoodsSpecInfo getSelectGoosInfo(LitemallGoodsProduct litemallGoodsProduct){
        SelectedGoodsSpecInfo selectedGoodsSpecInfo = new SelectedGoodsSpecInfo();
        if(litemallGoodsProduct != null){
            List<LitemallGoodsProductSpecification> specifications
                    = JSON.parseArray(litemallGoodsProduct.getSpecifications(), LitemallGoodsProductSpecification.class);
            if(specifications.size() > 0){
                selectedGoodsSpecInfo.setId(specifications.get(0).getId());
                selectedGoodsSpecInfo.setStock(1);
                return selectedGoodsSpecInfo;
            }
        }
        return new SelectedGoodsSpecInfo();
    }



    /**
     * 获取 specList、skuList
     * @param goods
     * @return
     */
    public GoodsDataSku getSkuItemList(StoreGoodsVo goods) {
        // 商品SKU信息 goods_sku
        GoodsDataSku goodsDataSku = new GoodsDataSku();
        //商品自身属性SKU规格分类选项列表数据（选择多个SKU规格后，得到用户最终选择的SKU商品和价格信息）
        List<GoodsSpecInfo> goodsSpecDataInfoList = getGoodsSpecDataInfo(goods.getId(),AgedmallGoodsSpecificationInfoConstant.TYPE_ONINE,goods.getServiceId());
        goodsDataSku.setSpecList(goodsSpecDataInfoList);

        //商品已上架的SKU商品列表数据，即联动SKU规格分类最终选出来的商品是列表中的某个SKU商品，或未上架的SKU商品
        List<GoodsSkuInfo> skuItemInfoList = getSkuItemInfoList(goods);
        goodsDataSku.setSkuList(skuItemInfoList);
        return goodsDataSku;
    }

    /**
     * 商品规格公用
     * @return
     */
    @SuppressWarnings("all")
    private List<GoodsSpecInfo> getGoodsSpecDataInfo(Integer id, String type,Integer serviceId){
        //商品自身属性SKU规格分类选项列表数据（选择多个SKU规格后，得到用户最终选择的SKU商品和价格信息）
        List<AgedmallGoodsSpecificationInfo> goodsSpecificationInfoList = agedmallGoodsSpecificationInfoService.getByGoodsIdAndType(serviceId, type);
        List<GoodsSpecInfo> goodsSpecInfoList = new ArrayList<>(goodsSpecificationInfoList.size());
        for(AgedmallGoodsSpecificationInfo asf : goodsSpecificationInfoList){
            GoodsSpecInfo goodsSpecInfo = new GoodsSpecInfo();
            goodsSpecInfo.setId(asf.getId());
            goodsSpecInfo.setName(asf.getSpecName());

            LitemallGoodsSpecificationExample example = new LitemallGoodsSpecificationExample();
            example.or().andParentIdEqualTo(asf.getId());
            List<LitemallGoodsSpecification> litemallGoodsSpecificationList  = litemallGoodsSpecificationMapper.selectByExample(example);
            List<GoodsSpecItemInfo> list = new ArrayList<>(litemallGoodsSpecificationList.size());
            for(LitemallGoodsSpecification lgs : litemallGoodsSpecificationList){
                GoodsSpecItemInfo goodsSpecItemInfo = new GoodsSpecItemInfo();
                goodsSpecItemInfo.setId(lgs.getId());
                goodsSpecItemInfo.setName(lgs.getValue());
                goodsSpecItemInfo.setImage(lgs.getPicUrl());
                list.add(goodsSpecItemInfo);
            }
            goodsSpecInfo.setList(list);

            goodsSpecInfoList.add(goodsSpecInfo);
        }
        return goodsSpecInfoList;
    }


    /**
     * 商品已上架的SKU商品列表数据，
     * 即联动SKU规格分类最终选出来的商品是列表中的某个SKU商品，或未上架的SKU商品
     * @param goods
     * @return
     */
    private List<GoodsSkuInfo> getSkuItemInfoList(StoreGoodsVo goods) {
        //根据在线服务id查询litemall_goods_product表信息
        LitemallGoodsProductExample example = new LitemallGoodsProductExample();
        example.or().andGoodsIdEqualTo(goods.getServiceId())
                    .andTypeEqualTo(AgedmallGoodsSpecificationInfoConstant.TYPE_ONINE);
        List<LitemallGoodsProduct> litemallGoodsProductList = litemallGoodsProductMapper.selectByExample(example);
        List<GoodsSkuInfo> goodsSkuInfoList = new ArrayList<>();
        for(LitemallGoodsProduct lgp : litemallGoodsProductList){
            HashSet<Integer> set = new HashSet<>();
            GoodsSkuInfo goodsSkuInfo = new GoodsSkuInfo();
            goodsSkuInfo.setSkuId(lgp.getId());//skuId
            goodsSkuInfo.setStock(1);
            //SKU商品规格ID数组，例如: [1002,2002,3001]
            List<LitemallGoodsProductSpecification> specificationList
                    = JSONObject.parseArray(lgp.getSpecifications(), LitemallGoodsProductSpecification.class);

            for(LitemallGoodsProductSpecification gd : specificationList){
                set.add(gd.getId());
            }
           /* List<Integer> list = new ArrayList<>();
            for(Integer s : set){
                list.add(s);
            }*/
            //设置服务价格priceInfo
            PriceInfo priceInfo = new PriceInfo();
            priceInfo.setPrice(goods.getServicePrice());
           // AgedmallOnlineService agedmallOnlineService = agedmallOnlineServiceMapper.selectByPrimaryKey(goods.getServiceId());
            //priceInfo.setLinePrice(agedmallOnlineService.getOriginalPrice());
            priceInfo.setLinePrice(goods.getOriginalPrice());
            priceInfo.setSuffix(goods.getUnit());
            goodsSkuInfo.setPriceInfo(priceInfo);
            goodsSkuInfo.setSpecIds(new ArrayList<>(set));
            goodsSkuInfoList.add(goodsSkuInfo);
        }
        return goodsSkuInfoList;
    }

}
